package com.core.handler;

import com.alibaba.fastjson2.JSON;
import com.core.constant.CharSetConstant;
import com.core.resp.AjaxResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author : HUANG
 * @create : 2025/6/1 18:23
 * @function : 处理认证异常的类
 */
@Slf4j
@Configuration
public class AuthenticationEntryPointHandler implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        log.warn("请求访问：{}，认证失败，无法访问系统资源",request.getRequestURI());
        int code = 401;
        String msg = "请求访问：{" + request.getRequestURI() + "}，认证失败，无法访问系统资源";
        response.setCharacterEncoding(CharSetConstant.CHAR_SET);
        response.getWriter().print(JSON.toJSONString(AjaxResponse.error(code, msg)));
    }
}
